package org.jeecg.modules.com.pointoperation.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import net.bytebuddy.asm.Advice;
import org.apache.poi.hslf.model.Fill;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.com.pointoperation.entity.Fillintegralrecord;
import org.jeecg.modules.com.pointoperation.entity.PackageInfo;
import org.jeecg.modules.com.pointoperation.entity.VerifyConsumeRecord;
import org.jeecg.modules.com.pointoperation.service.*;
import org.jeecg.modules.com.pointoperation.utils.ComponentUtils;
import org.jeecg.modules.com.qrcodeproductlist.entity.QrcodeProductList;
import org.jeecg.modules.com.qrcodeproductlist.service.IQrcodeProductListService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 补积分记录
 * @Author: jeecg-boot
 * @Date:   2020-05-05
 * @Version: V1.0
 */
@Api(tags="补积分记录")
@RestController
@RequestMapping("/org.jeecg.modules.com.pointoperation/fillintegralrecord")
@Slf4j
public class FillintegralrecordController extends JeecgController<Fillintegralrecord, IFillintegralrecordService> {
	@Autowired
	private IFillintegralrecordService fillintegralrecordService;
	@Autowired
    private IUserspointService userspointService;
	@Autowired
    private IPointflowService pointflowService;
	@Autowired
    private IVerifyConsumeRecordService verifyConsumeRecordService;
	 @Autowired
	 private IPackageInfoService packageInfoService;
	 @Autowired
	 private IQrcodeProductListService qrcodeProductListService;

	/**
	 * 分页列表查询
	 *
	 * @param fillintegralrecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "补积分记录-分页列表查询")
	@ApiOperation(value="补积分记录-分页列表查询", notes="补积分记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Fillintegralrecord fillintegralrecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Fillintegralrecord> queryWrapper = QueryGenerator.initQueryWrapper(fillintegralrecord, req.getParameterMap());
		Page<Fillintegralrecord> page = new Page<Fillintegralrecord>(pageNo, pageSize);
		IPage<Fillintegralrecord> pageList = fillintegralrecordService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param fillintegralrecord
	 * @return
	 */
	@AutoLog(value = "补积分记录-添加")
	@ApiOperation(value="补积分记录-添加", notes="补积分记录-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody Fillintegralrecord fillintegralrecord , Integer qrcodeid , String outercode) {
//		fillintegralrecordService.save(fillintegralrecord);
		String channel = new String();
		Integer activityId = new Integer(0);

		log.info("select option is "+qrcodeid);
		log.info("select option is "+fillintegralrecord.toString());

		if ( ! StringUtils.hasLength(fillintegralrecord.getChannel()) ) {
			log.warn("所补积分未选择渠道");
			return Result.error("所补积分未选择渠道");
		}else if(fillintegralrecord.getChannel().equals("BJQ2")){
			channel = "BJQ2";
			activityId = 500;

		} else if (fillintegralrecord.getChannel().equals("xlkv3")) {
			channel = "xlkv3";
			activityId = 400;
		}else{
			log.warn("所补积分既不是BJQ2也不是xlkv3");
			return Result.error("所补积分既不是BJQ2也不是xlkv3");
		}

		String packageCode ;
		String codeType;
		if (StringUtils.hasLength(fillintegralrecord.getInnercode())) {
			packageCode = fillintegralrecord.getInnercode();
			codeType = "1";
		} else if (StringUtils.hasLength(fillintegralrecord.getOutercode())) {
			packageCode = fillintegralrecord.getOutercode();
			codeType = "2";
		}else{
			log.warn("未输入袋内外码");
			return Result.error("未输入袋内外码");
		}

		JSONObject jsonObject = ComponentUtils.sendHttpRequestByGet("https://qr.huggies.com.cn:8099/openapi/proj/codequery/query?codeType="+codeType+"&code=" + packageCode,
				"ehsure@2017",
				"8BiUk$.)tpJ8wt$Cs[p0Sjv+[*iF^p");

		log.info(jsonObject.toJSONString());
		JSONObject jsondate = jsonObject.getJSONObject("data");

		fillintegralrecord.setInnercode(jsondate.getString("eptCode"));
		fillintegralrecord.setOutercode(jsondate.getString("code"));

			Fillintegralrecord fillintegralrecordTemp = fillintegralrecordService.fillIntegralRecord(fillintegralrecord);
		VerifyConsumeRecord verifyConsumeRecord = new VerifyConsumeRecord();

		verifyConsumeRecord.setBono(fillintegralrecordTemp.getBono());
		verifyConsumeRecord.setQrCode(fillintegralrecord.getInnercode());
		verifyConsumeRecord.setVerifyConsumeTime(new Date());
		verifyConsumeRecord.setUserNo(fillintegralrecord.getAppletopenid());
		verifyConsumeRecord.setLotteryInfoId(0);
		verifyConsumeRecord.setActivityId(activityId);

		String ProjectId = fillintegralrecord.getProject();
		qrcodeid = Integer.parseInt(ProjectId);
		log.info(qrcodeid+ " $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
		log.info(qrcodeid+ " $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
		QrcodeProductList qrcodeProductList = qrcodeProductListService.getById(qrcodeid);

		PackageInfo packageInfo = new PackageInfo();
//		packageInfo.setFullName(qrcodeProductList.getPackagename().substring(0,4));
		packageInfo.setFullName(qrcodeProductList.getPackagename());
		packageInfo.setEptCode(verifyConsumeRecord.getQrCode());
		packageInfo.setCode(fillintegralrecord.getOutercode());
		packageInfo.setSku(qrcodeProductList.getErpcode());
		packageInfo.setUserNo(fillintegralrecord.getAppletopenid());
		packageInfo.setQrCode(verifyConsumeRecord.getQrCode());
		packageInfo.setStatus(1);

		if (channel.equals("BJQ2")) {
			verifyConsumeRecordService.insertVerifyRecord(verifyConsumeRecord);
			packageInfoService.insertPackageInfo(packageInfo);

		}

		if (channel.equals("xlkv3")) {
			verifyConsumeRecordService.insertVerifyRecord2(verifyConsumeRecord);
			packageInfoService.insertPackageInfo(packageInfo);

		}


		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param fillintegralrecord
	 * @return
	 */
	@AutoLog(value = "补积分记录-编辑")
	@ApiOperation(value="补积分记录-编辑", notes="补积分记录-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody Fillintegralrecord fillintegralrecord) {
		fillintegralrecordService.updateById(fillintegralrecord);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "补积分记录-通过id删除")
	@ApiOperation(value="补积分记录-通过id删除", notes="补积分记录-通过id删除")
	@DeleteMapping(value = "/delete")
	@RequiresRoles(value = "admin")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		fillintegralrecordService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "补积分记录-批量删除")
	@ApiOperation(value="补积分记录-批量删除", notes="补积分记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@RequiresRoles(value = "admin")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fillintegralrecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "补积分记录-通过id查询")
	@ApiOperation(value="补积分记录-通过id查询", notes="补积分记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Fillintegralrecord fillintegralrecord = fillintegralrecordService.getById(id);
		if(fillintegralrecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(fillintegralrecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fillintegralrecord
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Fillintegralrecord fillintegralrecord) {
        return super.exportXls(request, fillintegralrecord, Fillintegralrecord.class, "补积分记录");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Fillintegralrecord.class);
    }

}
